<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/8/7
 * Time: 12:59
 */

namespace app\modules\mch\models;

use app\models\GoodsLevelPrice;

class GoodsLevelPriceFrom extends Model
{
    public $goods_id;

    public $store_id;
    
    public $goods_level_price;


    /**
     * @return array
     */
    public function rules()
    {
        return [
            [['level_price', 'level_cost_price', 'level_original_price'], 'number'],
            [['price',], 'number', 'min' => 0.01,],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'store_id' => 'Store ID',
            'level_price' => '等级 售价',
            'level_cost_price' => '等级 成本价',
            'level_original_price' => '等级 原价',
        ];
    }




    /**
     * 编辑
     * @return array
     */
    public function save()
    {
        $store_id = $this->store_id;
        $goods_id = $this->goods_id;
        $goods_level_price = $this->goods_level_price;

        // return $this->goods_level_price;

        foreach ($goods_level_price as $k => $v) {
            $GoodsLevelPrice = new GoodsLevelPrice();
            $data = GoodsLevelPrice::find()
            ->where([
                'level_id' => $k,
                'store_id' => $store_id, 
                'goods_id' => $goods_id
            ])->asArray()->one();

            // 修改
            if($data != null)
            {
                $GoodsLevelPriceData = [];
                $GoodsLevelPriceData['level_id'] = $k;
                $GoodsLevelPriceData['store_id'] = $store_id;
                $GoodsLevelPriceData['goods_id'] = $goods_id;
                $GoodsLevelPriceData['level_price'] = $v['level_price'];
                $GoodsLevelPriceData['level_cost_price'] = $v['level_cost_price'];
                $GoodsLevelPriceData['level_original_price'] = $v['level_original_price'];
                $GoodsLevelPrice->updateAll(
                    $GoodsLevelPriceData,
                    'id=:id',
                    [':id' => $data['id']]
                );
            }
            // 添加
            else
            {
                $GoodsLevelPrice->level_id = $k;
                $GoodsLevelPrice->store_id = $store_id;
                $GoodsLevelPrice->goods_id = $goods_id;
                $GoodsLevelPrice->level_price = $v['level_price'];
                $GoodsLevelPrice->level_cost_price = $v['level_cost_price'];
                $GoodsLevelPrice->level_original_price = $v['level_original_price'];
                $GoodsLevelPrice->save();
            }
        }
    }

    
}